package com.leyou.controller;

import com.leyou.api.TurnService;
import com.leyou.constant.ResponseMessage;
import com.leyou.constant.Result;
import com.leyou.domain.db1entity.TableCell;
import com.leyou.domain.db1entity.TurnTableActivity;
import com.leyou.domain.db3entity.Prscard;
import com.leyou.domain.vo.StartTurnVO;
import com.leyou.domain.vo.TurnRecordVO;
import com.leyou.domain.vo.TurnTableActivityInfoVO;
import com.leyou.utils.Utils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author lixin
 * @Date 2018/11/22 10:18
 * @Version 1.0
 * @Description TODO
 **/
@RequestMapping("turn")
@RestController
public class TurnController {


    @Autowired
    TurnService turnService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @PostMapping("getTurnTableActivityInfoVO")
    ResponseMessage getTurnTableActivityInfoVO(@RequestBody TurnTableActivity turnTableActivity) {
        TurnTableActivityInfoVO turnTableActivityInfoVO = null;
        if (StringUtils.isBlank(turnTableActivity.getActivitykey())) {
            return Result.error(400000, "活动主键为空");
        } else {
            turnTableActivityInfoVO = turnService.getTurnTableActivityInfoVO(turnTableActivity.getActivitykey());
        }
        return Result.success(turnTableActivityInfoVO);
    }

    @PostMapping("startTurn")
    ResponseMessage startTurn(@RequestBody StartTurnVO startTurnVO,
                              @CookieValue(name = "ticket", required = false) String ticket) {


        if (StringUtils.isBlank(ticket)) {
            return Result.success(9, "登录");
        }

        if (!redisTemplate.hasKey(ticket)) {
            return Result.success(9, "登录");
        }

        ValueOperations<String, Prscard> opsForValue = redisTemplate.opsForValue();
        Prscard prscard = opsForValue.get(ticket);
        startTurnVO.setUserId(prscard.getIdcard());


        //拿到当前活动的所有信息
        TurnTableActivityInfoVO turnTableActivityInfoVO = turnService.getTurnTableActivityInfoVO(startTurnVO.getActivityKey());


        if (turnTableActivityInfoVO.getTableCellList() == null || turnTableActivityInfoVO.getTableCellList().size() == 0) {
            return Result.error(400000, "当前活动还未配置好请稍等");
        }



        //拿到当前的用户卡号
        String cardNum = turnService.getCardNumByUserId(startTurnVO.getUserId());

        System.out.println(cardNum);
        System.out.println(startTurnVO.getActivityKey());
        System.out.println(startTurnVO.getUserId());



        //判断转盘条件
        switch (turnTableActivityInfoVO.getConditionPutVO().getConditiontype()) {
            case "0":
                //无条件
                if (turnService.getActivityTryCountByUserId(startTurnVO) > turnTableActivityInfoVO.getConditionPutVO().getMaxtry()) {
                    return Result.error(400000, "您的机会用完了,请下次再来");
                }
                break;
            case "1":
                int currentPonts = 0;
                //验证积分数量
                if (turnTableActivityInfoVO.getConditionPutVO().getPoints() > currentPonts) {
                    return Result.error(400000, "您的积分不足请购买商品增加积分,当前积分" + currentPonts);
                }
                break;
            case "2":
                break;
            case "3":
                break;
            default:
                return Result.error(400000, "转盘条件数据错误");
        }

        //得到随机奖项
        TableCell prize = Utils.getPrize(turnTableActivityInfoVO.getTableCellList());

        //此奖已发完
        if (!prize.getCelltype().equals("4")) {
            if (prize.getCount() <= 0) {
                //随机得到一个可用奖项
                prize = turnService.getAvailableTableCell(turnTableActivityInfoVO.getActivitykey());
            }
        }


        //当前奖品限制了日最大领取数
        if (prize.getMaxGet() > 0) {

            //验证当日领取数
            if (!turnService.isPrizeAvaiable(prize, turnTableActivityInfoVO.getActivitykey())) {
                //当前超过最大次数
                //得到一个可用奖项
                prize = turnService.getAvailableTableCell(turnTableActivityInfoVO.getActivitykey());
            }
        }

        //发奖
        try {
            turnService.sendPrize(prize, startTurnVO, cardNum, turnTableActivityInfoVO);
        } catch (Exception e) {
            return Result.error(400000, e.getMessage());
        }
        //积分抽奖削减积分
        if ("2".equals(turnTableActivityInfoVO.getConditionPutVO().getConditiontype())) {
            //减积分
        }

        //生成领奖记录
        rabbitTemplate.convertAndSend("prizeQueue", new TurnRecordVO(prize, startTurnVO.getUserId(), cardNum));
        return Result.success(prize);

    }


    @PostMapping("getUserInfoByTicket")
    public ResponseMessage getUserInfoByTicket(@CookieValue(name = "ticket", required = false) String ticket) {
        ValueOperations<String, Prscard> valueOperations = redisTemplate.opsForValue();
        Prscard prscard = valueOperations.get(ticket);
        return Result.success(200000, "成功", prscard);
    }


    @PostMapping("login")
    ResponseMessage login(String username, String password, HttpServletResponse response) {
        Prscard prscard = turnService.selectUser(username, password);
        if (prscard == null) {
            return Result.error(-1, "账户密码错误");
        }

        String ticket = UUID.randomUUID().toString().substring(0, 20);

        ValueOperations<String, Prscard> opsForValue = redisTemplate.opsForValue();

        redisTemplate.opsForValue().set(ticket, prscard, 30, TimeUnit.MINUTES);

        Cookie cookie = new Cookie("ticket", ticket);

        cookie.setPath("/");

        cookie.setMaxAge(1800);

        response.addCookie(cookie);

        return Result.success(0, "成功");
    }


}

